package io;

import java.io.File;
import java.util.*;

//图片管理类
public class ImageManager {
    private Map<String,String> imageMap;//Key:图片名，Value：本地路径
    private Set<String> supportedFormats;//支持的文件格式

    public ImageManager(){
        imageMap = new HashMap<>();
        supportedFormats = new HashSet<>(Arrays.asList("jpg", "jpeg", "png", "gif", "bmp", "webp"));
        loadExistingImages();//启动时加载已下载的图片
    }

    //下载图片
    public void downloadImage(String url){
        try{
            //验证URl格式
            if (!url.startsWith("http")){
                System.out.println("格式错误：URL必须以http或https开头");
                    return;
            }

            //提取文件名
            String fileName = extractFileName(url);
            if (fileName.isEmpty()){
                System.out.println("无法从URL中提取文件名");
                return;
            }

            //检验文件格式
            String fileExtension = getFileExtension(fileName).toLowerCase();

            if (!supportedFormats.contains(fileExtension)){
                System.out.println("不支持该图片格式"+fileExtension);
                System.out.println("支持的图片格式："+supportedFormats);
            }

            //确保images目录存在
            FileUtils.ensureDirectoryExists("images");

            //处理文件名冲突
            String savePath = "images/" + fileName;
            File file = new File(savePath);
            if (file.exists()){
                String baseName = fileName.substring(0,fileName.lastIndexOf('.'));
                String extension = fileName.substring(fileName.lastIndexOf('.'));
                int counter = 1;
                do {
                    fileName = baseName + "_" + counter + extension;
                    savePath = "images/" + fileName;
                    file = new File(savePath);
                    counter++;
                }while (file.exists());
            }

            //下载图片
            FileUtils.saveImage(url,savePath);

            //更新
            imageMap.put(fileName,savePath);

            //记录日志
            FileUtils.appendlog("Downloaded:" + url + "->" + savePath);
        }catch (Exception e){
            System.out.println("下载失败：" + e.getMessage());
            FileUtils.appendlog("Failed: " + url + "-Error" + e.getMessage());
        }
    }

    //加载已存在的图片
    public void loadExistingImages(){
        File imagesDir = new File("images");
        if (imagesDir.exists() && imagesDir.isDirectory()){
            File[] files = imagesDir.listFiles((dir, name) -> {
                String ext = getFileExtension(name).toLowerCase();
                return supportedFormats.contains(ext);
            });
            if (files != null){
                for (File file : files){
                    imageMap.put(file.getName(),file.getPath());
                }
            }
        }
    }

    //列出所有已下载的图片
    public void listImages(){
        if (imageMap.isEmpty()){
            System.out.println("暂无已下载的图片");
            return;
        }

        System.out.println("===已下载的图片列表===");
        System.out.printf("%-30s %-50s\n", "图片名称", "保存路径");
        System.out.println("----------------------------------------------------------------");

        int index = 1;
        for (Map.Entry<String, String> entry : imageMap.entrySet()){
            System.out.printf("%-30s %-50s\n",index + "." + entry.getKey(),entry.getValue());
            index++;
        }
        System.out.printf("总计：" + imageMap.size() + "张图片");
    }

    //搜索图片
    public void searchImage(String keyword){
        List<String> results = new ArrayList<>();

        for (String fileName : imageMap.keySet()){
            if(fileName.toLowerCase().contains(keyword.toLowerCase())){
                results.add(fileName);
            }
        }

        if (results.isEmpty()){
            System.out.println("未找到包含'" + keyword + "'的图片");
            return;
        }

        System.out.println("===搜寻结果===");
        for (String fileName : results){
            System.out.println("图片名称 ：" +fileName);
            System.out.println("保存路径：" + imageMap.get(fileName));
            System.out.println("----------------------");
        }
        System.out.println("找到" + results.size() + "张匹配的图片");
    }

    //从URL中提取文件名
    private String extractFileName(String url){
        try {
            //移除URL参数
            String cleanUrl = url.split("\\?")[0];
            String fileName = cleanUrl.substring(cleanUrl.lastIndexOf("/") + 1);

            //如果文件名为空或太长，生成随机文件名
            if (fileName.isEmpty() || fileName.length() > 100){
                fileName = "image_" + System.currentTimeMillis() + ".jpg";
            }
            return fileName;
        }catch (Exception e){
            return "image_" + System.currentTimeMillis() + ".jpg";
        }
    }

    //获取文件扩展名
    private String getFileExtension(String fileName){
        int lastDotIndex = fileName.lastIndexOf(".");
        if (lastDotIndex>0){
            return fileName.substring(lastDotIndex + 1);
        }
        return  "";
    }

    //获取图片数量
    public int getImageCount(){
        return imageMap.size();
    }
}
